<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace Game\Module;


use Game\Config\Config;
use Workerman\MySQL\Connection;

/**
 * 数据库类
 */
class Mysql
{
    /**
     * 实例数组
     * @var array
     */
    protected static $instance = array();

    /**
     * 获取实例
     * @param string $config_name
     * @return Connection
     */
    public static function instance($config_name='DB') {

        if(empty(self::$instance[$config_name])) {
            try {
                self::$instance[$config_name] = new Connection(Config::DB_Host, Config::DB_Port, Config::DB_User, Config::DB_Password, Config::DB_Name, Config::DB_Charset);
            }catch (\Exception $exception){
                Logger::getInstance()->error("数据库连接失败");
                //throw new \Exception($exception->getMessage());
                return false;
            }
        }
        return self::$instance[$config_name];
    }

    /**
     * 关闭数据库实例
     * @param string $config_name
     */
    public static function close($config_name) {
        if(isset(self::$instance[$config_name])){
            self::$instance[$config_name]->closeConnection();
            self::$instance[$config_name] = null;
        }
    }

    /**
     * 关闭所有数据库实例
     */
    public static function closeAll(){
        foreach(self::$instance as $connection){
            $connection->closeConnection();
        }
        self::$instance = array();
    }
}
